package com.richie696.catalina;

import java.io.File;
import java.util.*;

public class MappedHost implements Host {

    private String name;
    private final Map<String, List<Wrapper>> wrappers = new HashMap<>(5);
    private Wrapper defaultWrapper;
    private String appBase;
    private File appBaseFile;

    public MappedHost(String name, String appBase) {
        this.name =  name;
        this.appBase = appBase;
        setAppBaseFile();
    }

    @Override
    public String getName() {
        return this.name;
    }

    @Override
    public void setName(String name) {
        this.name = name;
    }

    @Override
    public List<Wrapper> getWrappers() {
        return this.wrappers.get(this.appBase);
    }

    @Override
    public Wrapper getDefaultWrapper() {
        return this.defaultWrapper;
    }

    @Override
    public Wrapper getWrapper(String warName) {
        List<Wrapper> wrappers = this.wrappers.get(this.appBase);
        return wrappers.stream().filter(w -> w.getName().equalsIgnoreCase(warName)).findFirst().orElse(defaultWrapper);
    }

    @Override
    public void addWrapper(Wrapper wrapper) {
        List<Wrapper> wrappers = this.wrappers.get(this.appBase);
        if (Objects.isNull(wrappers)) {
            wrappers = new ArrayList<>(5);
            this.wrappers.put(appBase, wrappers);
        }
        wrappers.add(wrapper);
        if ("ROOT".equalsIgnoreCase(wrapper.getName())) {
            this.defaultWrapper = wrapper;
        }
    }

    @Override
    public String getAppBase() {
        return this.appBase;
    }

    @Override
    public void setAppBase(String appBase) {
        this.appBase = appBase;
        setAppBaseFile();
    }

    @Override
    public File getAppBaseFile() {
        return appBaseFile;
    }

    public void setAppBaseFile() {
        String path = Objects.requireNonNull(MappedHost.class.getClassLoader().getResource(appBase)).getPath();
        appBaseFile = new File(path);
    }
}
